package com.ruoyi.tb.lmt.controller;

import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.tb.lmt.domain.bo.*;
import com.ruoyi.tb.lmt.domain.vo.TbMutualInspectionVo;
import com.ruoyi.tb.lmt.service.*;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbSpecialInspectionVo;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 专检主表
 *
 * @author ruoyi
 * @date 2024-01-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/specialInspection")
public class TbSpecialInspectionController extends BaseController {

    private final ITbSpecialInspectionService iTbSpecialInspectionService;

    @Autowired
    private ITbRepairplanlistService iTbRepairplanlistService;

    @Autowired
    private ITbLmtrepairWorkdetailService iTbLmtrepairWorkdetailService;

    @Autowired
    private ITbAcceptanceService iTbAcceptanceService;

    @Autowired
    private ITbLocomotiveService iTbLocomotiveService;

    /**
     * 查询专检主表列表
     */
    @GetMapping("/list")
    public TableDataInfo<TbSpecialInspectionVo> list(TbSpecialInspectionBo bo, PageQuery pageQuery) {
        return iTbSpecialInspectionService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出专检主表列表
     */
    @Log(title = "专检主表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbSpecialInspectionBo bo, HttpServletResponse response) {
        List<TbSpecialInspectionVo> list = iTbSpecialInspectionService.queryList(bo);
        ExcelUtil.exportExcel(list, "专检主表", TbSpecialInspectionVo.class, response);
    }

    /**
     * 获取专检主表详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<TbSpecialInspectionVo> getInfo(@NotNull(message = "主键不能为空")
                                            @PathVariable Long id) {
        return R.ok(iTbSpecialInspectionService.queryById(id));
    }

    /**
     * 新增专检主表
     */
    @SaCheckPermission("xha-lmt:specialInspection:add")
    @Log(title = "专检主表", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody List<TbSpecialInspectionBo> boList) {
        for (TbSpecialInspectionBo bo : boList) {
            TbSpecialInspectionBo bos = iTbSpecialInspectionService.selectByBo(bo);
            iTbSpecialInspectionService.insertByBo(bos);
        }
        return toAjax(boList.size());
    }

    /**
     * 修改专检主表
     */
    @SaCheckPermission("xha-lmt:specialInspection:edit")
    @Log(title = "专检主表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbSpecialInspectionBo bo) {
        return toAjax(iTbSpecialInspectionService.updateByBo(bo));
    }

    /**
     * 删除专检主表
     *
     * @param ids 主键串
     */
    @SaCheckPermission("xha-lmt:specialInspection:remove")
    @Log(title = "专检主表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTbSpecialInspectionService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    //查询专检主表
    @GetMapping("/list/selectBySpecial")
    public TableDataInfo<TbSpecialInspectionVo> selectBySpecial(String id, String lmtType, String lmtNumber, String status, String repairChar, String planName, String workGroup, String workUser, PageQuery pageQuery) {
        return iTbSpecialInspectionService.selectBySpecial(id, lmtType, lmtNumber, status, repairChar, planName, workGroup, workUser, pageQuery);
    }

    /**
     * 审批设置专检工队，要设置权限
     */
    @SaCheckPermission("xha-lmt:specialInspection:updateDispatch")
    @Log(title = "审批专检主表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("update/dispatch")
    public R<Void> updateDispatch(@Validated(EditGroup.class) @RequestBody TbSpecialInspectionBo bo) {
        bo.setStatus("待派活");
        TbRepairplanlistBo rplBo = new TbRepairplanlistBo();
        rplBo.setId(bo.getLmtRepairId());
        rplBo.setStatus("专检中");
        iTbRepairplanlistService.updateByBo(rplBo);
        return toAjax(iTbSpecialInspectionService.updateByBo(bo));
    }

    /**
     * 设置专检人员
     */
    @SaCheckPermission("xha-lmt:specialInspection:updateUser")
    @Log(title = "设置专检人员", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("update/user")
    public R<Void> updateUser(@Validated(EditGroup.class) @RequestBody TbSpecialInspectionBo bo) {
        bo.setStatus("专检中");
        bo.setSendToUserTime(new Date());
        return toAjax(iTbSpecialInspectionService.updateByBo(bo));
    }

    /**
     * 设置专检通过
     */
    @SaCheckPermission("xha-lmt:specialInspection:updateApproval")
    @Log(title = "专检通过", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("update/approval")
    public R<Void> updateApproval(@Validated(EditGroup.class) @RequestBody TbSpecialInspectionBo bo) {
        bo.setStatus("已完成");
        bo.setWorkUser(LoginHelper.getUsername());
        bo.setWorkGroupId(LoginHelper.getDeptId());
        bo.setWorkGroup(LoginHelper.getLoginUser().getDeptName());
        TbRepairplanlistBo rplBo = new TbRepairplanlistBo();
        rplBo.setId(bo.getLmtRepairId());

        //设置检修中的专检任务完成
        Long lmtRepairId = bo.getLmtRepairId();
        TbLmtrepairWorkdetailBo lmtBo = iTbLmtrepairWorkdetailService.selectBySpecial(lmtRepairId);
        if (lmtBo != null) {
            //查询专检问题，并且设置完成
            lmtBo.setStatus("已完成");
            lmtBo.setEndTime(new Date());
            iTbLmtrepairWorkdetailService.updateByBo(lmtBo);
        }

        if (iTbRepairplanlistService.isTypeById(bo.getLmtRepairId())) {

            rplBo.setStatus("已完成");

            //给二级修的大机设置成运行中
            Long lmtId = iTbLocomotiveService.selectByLmtId(bo.getLmtRepairId());
            TbLocomotiveBo lmtLocBo = new TbLocomotiveBo();
            lmtLocBo.setID(lmtId);
            lmtLocBo.setStatus("运行中");

            iTbLocomotiveService.updateByBo(lmtLocBo);
            // todo 判断是否所有任务都已完成,现在不加限制
            /*
            if (!iTbLmtrepairWorkdetailService.isFinishByLmtId(String.valueOf(bo.getLmtRepairId())) || !iTbLmtrepairWorkdetailService.isIssuesByLmtId(String.valueOf(bo.getLmtRepairId()))) {
                throw new RuntimeException("存在未完成任务或遗留问题未审批通过，无法完成专检任务。");
            }*/
        } else {
            rplBo.setStatus("专检完成");
        }
        LoginUser currentUser = LoginHelper.getLoginUser();
        rplBo.setCheckUser2(currentUser.getUsername());
        rplBo.setCheckTime2(new Date());
        iTbRepairplanlistService.updateByBo(rplBo);


        //判断是否为三级修和四级修
        if (iTbRepairplanlistService.isTwoTypeById(bo.getLmtRepairId())) {
            //当专检通过时，生成验收表数据
            TbAcceptanceBo bos = new TbAcceptanceBo();
            bos.setLmtRepairId(bo.getLmtRepairId());
            bos.setPlanId(bo.getPlanId());
            bos.setPlanName(bo.getPlanName());
            bos.setLmtType(bo.getLmtType());
            bos.setLmtNumber(bo.getLmtNumber());
            bos.setWorkerTeam(bo.getWorkerTeam());
            bos.setWorkGroup(bo.getWorkGroup());
            bos.setWorkGroupId(bo.getWorkGroupId());
            bos.setRepairChar(bo.getRepairChar());
            bos.setRepairType(bo.getRepairType());
            bos.setRepairTimes(bo.getRepairTimes());
            bos.setRepairCode(bo.getRepairCode());
            bos.setRepairStartDate(bo.getRepairStartDate());
            bos.setStatus("验收中");
            //设置完实体类，调用互检新增方法
            TbAcceptanceBo bo1 = iTbAcceptanceService.selectByBo(bos);
            iTbAcceptanceService.insertByBo(bo1);
        }

        return toAjax(iTbSpecialInspectionService.updateByBo(bo));
    }


    @Log(title = "修改专检问题数", businessType = BusinessType.UPDATE)
    @PutMapping("update/workNeed2")
    public R<Void> updateWorkNeed2(@Validated(EditGroup.class) @RequestBody TbSpecialInspectiondetailBo bo) {
        //service层处理传入的bo数据
        TbSpecialInspectionBo bos = new TbSpecialInspectionBo();
        bos.setId(bo.getMutualId());
        bos.setWorkNeed2(iTbSpecialInspectionService.updateWorkNeedByBo(bo.getMutualId()));
        return toAjax(iTbSpecialInspectionService.updateByBo(bos));
    }


}
